import wechat_util from "../utils/wechat_util";
import net_result from "../consts/net_result";
import { UserDao } from "../dao/user_dao";
import { LoginType } from "../consts/login_type";
import { Application, FrontendSession } from "pinus";
import { User } from "../entity/user.entity";

export class UserService{
    userList={};


    public static ins() : UserService{
        if (UserService._ins == null){
            UserService._ins = new UserService();
        }
        return UserService._ins;
    }

    private static _ins = null;


    async  loginByWechatMini(code){
        let token:any=await wechat_util.getSessionKey(code);
        if(token===null){
            return net_result.error(null,"获取小程序session失败");
        }
        else{
            return net_result.success(undefined,token);
        }
     }
     
     
     async loginByTest(app:Application,session: FrontendSession){
      
          let user=await UserDao.ins().findOrCreate(LoginType.Test,null);
          await this.setSessionUser(app,session,user);
          return net_result.success(null,{
              ...user
          });
     }

     private async setSessionUser(app:Application, session: FrontendSession,user:User){
            let sessionService = app.get('sessionService');
            if(!sessionService.getByUid(''+user.id)){
              await session.abind(''+user.id);
            }
            session.set("uid", user.id);
            session.set("pid",user.player.id);
            session.pushAll((err,res)=>{
                if(err){
                    console.error(err);
                }
            });
            // console.log("session",session);
            user.player.avatarUrl=user.avatarUrl;
            user.player.name=user.nickName;
            user.player.userId=""+user.id;
            user.player.init();
            await app.rpc.fight.fight_remote.add.route(session)(user.player,app.get("serverId"));
     }

}